package com.turtle3d;

import java.io.FileNotFoundException;
import java.util.Hashtable;

import javax.media.j3d.Shape3D;
import javax.vecmath.Color3f;

import com.sun.j3d.loaders.ParsingErrorException;
import com.sun.j3d.loaders.Scene;
import com.turtle3d.loaders.objectfile.ObjectFile;

/**
 * Singleton class for loading Shape3D objects.
 * 
 * @author Marek Paterczyk <marek.paterczyk@gmail.com>
 * 
 */
public class Shape3DCacheLoader {
	
	private static final String BASE_PATH = "objects";

	private static Shape3DCacheLoader shape3DCacheLoader = null;

	private Hashtable<String, Shape3D> shapes = new Hashtable<String, Shape3D>();

	public static Shape3DCacheLoader getShape3DCacheLoader() {
		if (shape3DCacheLoader == null)
			shape3DCacheLoader = new Shape3DCacheLoader();

		return shape3DCacheLoader;
	}

	public Shape3D createShape3D(String path) {
		if (shapes.containsKey(path))					
			return (Shape3D)(shapes.get(path)).cloneTree();		
		
		try {
			shapes.put(path, loadShape3D(path));
			return (Shape3D)(shapes.get(path)).cloneTree();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ParsingErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	private Shape3D loadShape3D(String path) throws FileNotFoundException, ParsingErrorException{
		boolean noTriangulate = false;
		boolean noStripify = false;
		float creaseAngle = 45f;

		int flags = 0;
		if (!noTriangulate)
			flags |= ObjectFile.TRIANGULATE;
		if (!noStripify)
			flags |= ObjectFile.STRIPIFY;
		ObjectFile f = new ObjectFile(flags,
				(float) (creaseAngle * Math.PI / 180.0));
		//ObjectFile objfile = new ObjectFile();
		//objfile.setBasePath(BASE_PATH);	
		f.setBasePath(BASE_PATH);
		
		Scene scene = null;
		
		scene = f.load(BASE_PATH+"/"+path+".obj");

		Shape3D shape = (Shape3D) scene.getSceneGroup().getChild(0);
		scene.getSceneGroup().removeChild(shape);
		
		Color3f c = new Color3f();
		shape.getAppearance().getMaterial().getDiffuseColor(c);
		//App.println(c);
		
		return shape;

	}
	
	/*private static void printGeometry(Shape3D shapein){
		
		Shape3D shape = (Shape3D)shapein.cloneNode(true); 
		shape.setCapability(Shape3D.ALLOW_GEOMETRY_READ);
				
		
		GeometryArray a = ((GeometryArray) shape.getGeometry());					
		a.setCapability(GeometryArray.ALLOW_REF_DATA_READ);
		
		
		Point3f verticesArray[] = new Point3f[a.getVertexCount()];		
		for (int i = 0; i < verticesArray.length; i++){
			verticesArray[i] = new Point3f();			
		}
		
		//a.getInterleavedVertexBuffer().getBuffer().
		a.getCoordinates(0, verticesArray);
		
		for(Point3f p:verticesArray)
			App.println(p);
	}*/

}
